package com.link4a.doms.dao.handler;

import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Repository;

import com.link4a.doms.dao.Page;
import com.link4a.doms.dao.SqlSessionTemplateSupport;
import com.link4a.doms.model.Role;
import com.link4a.doms.model.RolePermission;
import com.link4a.doms.vo.RoleCondition;

@Repository
public class RoleHandler extends SqlSessionTemplateSupport {

	public Page<Role> findPage(RoleCondition condition) {
		return findPage(condition, "countPage", "findPage");
	}
	
	public Role findById(int roleId) {
		return getSqlSession().selectOne("findById", roleId);
	}

	public List<Role> findAll() {
		return getSqlSession().selectList("findAll");
	}

	public void create(Role role) {
		SqlSession session = getSqlSession();
		session.insert("create", role);
		RolePermission relative = new RolePermission();
		relative.setRoleId(role.getId());
		for (String permission : role.getPermissions()) {
			relative.setPermissionName(permission);
			session.insert("addPermisson", relative);
		}
	}

	public void update(Role role) {
		getSqlSession().update("update", role);
		getSqlSession().delete("deleteRolePermissons", role.getId());
		RolePermission relative = new RolePermission();
		relative.setRoleId(role.getId());
		for (String permission : role.getPermissions()) {
			relative.setPermissionName(permission);
			getSqlSession().insert("addPermisson", relative);
		}
	}

	public void delete(int roleId) {
		getSqlSession().delete("delete", roleId);
	}

	public boolean checkRoleName(Role role, int flag) {
		Role dbRole = getSqlSession().selectOne("findByName", role.getName());
		if (dbRole == null) {
			return false;
		}
		if (flag == 0) {
			return dbRole.getName().equals(role.getName());
		} else if (flag == 1) {
			return dbRole.getName().equals(role.getName()) && dbRole.getId() != role.getId();
		}
		return true;
	}
}
